const app = getApp();
let province, city, area;
const CONFIRM_TEXT = "确认充值";
const APPLY_TEXT = "申请";
Page({
  data: {
    cardInfo: "", //查询到的水卡信息
    balance: 0, //充值账户余额
    card_number: "", //卡号
    promotions: [], //促销活动列表
    deposits: [], //押金设置
    templates: [], //充值模板
    showCard: false, //true充值 false开卡
    full_name: "",
    tel: "",
    village_name: "",
    village_id: "",
    templateIndex: '', //选中的模板下标
    priceList: [],
    giveList: [],
    moneyIndex: -1,
    give: 0,
    money: 0,
    custom: false,
    depositIndex: 0,
    btnTxt: APPLY_TEXT,
    isShow: true,
    showDeposit: true,
    userInfo: {},
    is_special: '', //1 是特殊水卡 2不是特殊水卡
    specialTips: false, //特殊水卡提醒
  },

  onShow: function () {
    this.getBalance();
    this.getDeposits();
    this.getDefaultVillage();
    this.getTemplateList();
  },

  hideCustom() {
    this.setData({
      custom: false
    })
  },
  chooseDeposit(e) {
    this.setData({
      depositIndex: e.currentTarget.dataset.index
    })
  },

  //切换充值模板
  templateChange(e) {
    var value = e.detail.value;
    if (this.data.templateIndex == value) {
      return false;
    }
    var template_data = this.data.templates[value].template;
    const temps = Object.values(template_data);
    let priceList = [],
      giveList = [];
    temps.forEach(current => {
      priceList.push(current.recharge);
      giveList.push(current.give);
    })
    this.setData({
      money: 0,
      give: 0,
      templateIndex: value,
      moneyIndex: "",
      priceList,
      giveList,
      template_id: this.data.templates[value].id
    })

  },

  //选择充值金额
  chooseMoney(e) {
    let index = e.currentTarget.dataset.index;
    let money = 0,
      give = 0;
    if (this.data.moneyIndex === index && index != -1) {
      return false;
    } else if (index == -1) {
      this.setData({
        custom: true,
        money: this.data.moneyIndex == -1 ? this.data.money : 0,
        give: this.data.moneyIndex == -1 ? this.data.give : 0,
        moneyIndex: index,
      })
    } else {
      money = parseFloat(this.data.priceList[index]);
      give = parseFloat(this.data.giveList[index]);
      this.setData({
        money,
        give,
        moneyIndex: index
      })
    }
  },

  //获取充值模板
  getTemplateList() {
    var that = this;
    app.ajax({
      url: 'Partner/Village/templateList',
      method: "POST",
      data: {
        row: 100,
        template_species: 3
      },
      success: function (res) {
        var flag = res.data;
        if (flag.code < 0) {
          app.showToast(flag.message);
          return false;
        }
        var template_index = '';
        const templates = res.data.data.data;
        let priceList = [],
          giveList = [],
          template_id = "";
        templates.forEach((item, index) => {
          if (item.is_default == 1) {
            template_index = index;
            template_id = item.id;
            const temps = Object.values(item.template);
            temps.forEach(current => {
              priceList.push(current.recharge);
              giveList.push(current.give);
            })
          }
        })
        that.setData({
          priceList,
          giveList,
          template_id,
          templates,
          templateIndex: template_index
        });
      }
    })
  },

  //选择园区
  chooseVillage() {
    let _self = this;
    wx.navigateTo({
      url: '../choiceCommunity/choiceCommunity',
      events: {
        acceptDataFromOpenedPage: function (village) {
          let village_name = village.village_name;
          _self.getPromotionByVillage(village.id)
          _self.setData({
            village_name,
            village_id: village.id,
          })
          province = village.province;
          city = village.city;
          area = village.area;
        }
      },
      success: function (res) {
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          village_id: _self.data.village_id
        })
      }
    })
  },


  //获取默认园区
  getDefaultVillage: function () {
    var that = this;
    app.ajax({
      url: 'Partner/WaterCard/getDefaultVillage',
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            village_name: res.data.data.village_name,
            village_id: res.data.data.id,
          })
          province = res.data.data.province;
          city = res.data.data.city;
          area = res.data.data.area;
          that.getPromotionByVillage(res.data.data.id);
        } else {
          province = "";
          city = "";
          area = "";
        }
      }
    });
  },

  handleInputCardNumber(e) {
    const value = e.detail.value;
    let data = {
      card_number: value,
    }
    if (value.trim() === "") {
      Object.assign(data, {
        cardInfo: "",
        showCard: false,
        isShow: true,
        btnTxt: APPLY_TEXT,
        moneyIndex: -1,
        money: 0,
        give: 0,
        specialTips: false,
      })
      if (this.data.cardInfo) {
        Object.assign(data, {
          tel: "",
          full_name: "",
          village_name: "",
          village_id: "",
          promotions: []
        })
      }
      this.setData(data)
    } else {
      this.setData({
        card_number: app.formatCard(value)
      })
    }
  },

  handleInput(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: e.detail.value
    })
  },


  //进入设置管理
  openManage() {
    let _self = this;
    wx.navigateTo({
      events: {
        acceptDataFromOpenedMange: function () {
          _self.getBalance();
        }
      },
      url: '../setManage/setManage',
      success: function (res) {
        res.eventChannel.emit("acceptDataFromOpenerWaterRecharge", {
          flag: 1
        });
      },
    })
  },
  //获取合伙人账户余额
  getBalance() {
    app.ajax({
      url: "Partner/WaterCard/getPartnerQuota",
      success: res => {
        if (res.data.code == 1000) {
          this.setData({
            userInfo: res.data.data,
            balance: res.data.data.account_recharge_balance
          })
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
        app.showToast("网络错误")
      }
    })
  },


  //获取押金配置
  getDeposits() {
    app.ajax({
      url: "Common/Common/cardDeposit",
      success: res => {
        if (res.data.code == 1000) {
          this.setData({
            deposits: res.data.data
          })
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
        app.showToast("网络错误")
      }
    })
  },

  //根据园区id来获取促销活动
  getPromotionByVillage(village_id) {
    app.ajax({
      url: "Partner/Promotion/getPromotionListByVillage",
      data: {
        village_id
      },
      success: res => {
        if (res.data.code === 1000) {
          this.setData({
            promotions: res.data.data,
          })
        }
      },
      error: () => {
        app.showToast("获取园区促销活动失败");
        return;
      }
    })
  },


  //选择促销活动
  choosePromotionItem(e) {
    const index = e.currentTarget.dataset.index;
    const list = this.data.promotions;
    this.setData({
      [`promotions[${index}].checked`]: !list[index].checked
    })
  },


  //获取水卡数据
  getWaterCard(card_number, isLoading = true) {
    isLoading && wx.showLoading({
      mask: true
    })
    app.ajax({
      url: "Partner/WaterCard/getWaterCard",
      data: {
        card: card_number
      },
      success: res => {
        isLoading && wx.hideLoading();
        const source = res.data;
        if (source.code > 0) {
          this.getPromotionByVillage(source.data.rq_id);
          this.setData({
            specialTips: source.data.is_special == 1 ? true : false,
            // moneyIndex: "",
            // money: 0,
            // give: 0,
            showCard: true,
            cardInfo: source.data,
            full_name: source.data.full_name || "",
            tel: source.data.tel || '',
            village_name: source.data.village_name || '',
            village_id: source.data.village_id || '',
            btnTxt: CONFIRM_TEXT,
            isShow: (!source.data.tel || !source.data.full_name || !source.data.village_name) ? true : false
          })
        } else {
          const obj = {
            cardInfo: "",
            showCard: false,
            btnTxt: APPLY_TEXT,
            isShow: true,
            moneyIndex: -1,
            money: 0,
            give: 0
          }
          if (this.data.cardInfo) {
            Object.assign(obj, {
              tel: "",
              full_name: "",
              village_name: "",
              village_id: "",
              promotions: [],
            })
          }
          this.setData(obj)
        }
      },
      error: e => {
        isLoading && wx.hideLoading();
        app.showToast("网络错误");
      }
    })
  },



  //根据卡号去查询水卡信息 存在为充值操作，反之为开卡操作
  fetchUserCard(e) {
    let card_number = app.trimAll(e.detail.value);
    if (card_number !== "") {
      this.getWaterCard(card_number);
    }
  },


  //扫码操作
  scanCode() {
    wx.scanCode({
      success: res => {
        res.result && this.setData({
          card_number: app.formatCard(res.result)
        })
        const card_number = app.trimAll(res.result);
        if (card_number === "") {
          app.showToast("请扫描正确的水卡号");
        } else {
          this.getWaterCard(card_number);
        }
      },
      fail: error => {
        console.log(error)
      }
    })
  },


  getPromotionIds() {
    let promotion_id = [];
    let promationList = this.data.promotions;
    if (promationList.length > 0) {
      promationList.forEach(item => {
        if (item.checked) {
          promotion_id.push(item.id)
        }
      })
    }
    return promotion_id;
  },

  hanldeSubmit() {
    const card_number = app.trimAll(this.data.card_number);
    if (card_number == "") {
      app.showToast("请输入卡号");
      return;
    }
    const type = this.data.showCard;
    const param = {};
    if (type === false) { //开卡操作
      Object.assign(param, {
        deposit: this.data.deposits[this.data.depositIndex]
      })
    }
    this.promotion_id = this.getPromotionIds();
    if (type) {
      if (this.data.moneyIndex === "") {
        if (this.data.promotions.length > 0 && this.promotion_id.length == 0) {
          app.showToast('请选择金额或者选择促销活动');
          return false;
        } else {
          app.showToast('请选择充值金额');
          return false;
        }
      } else {
        if (this.data.moneyIndex == -1 && this.data.money == 0) {
          app.showToast('自定义金额必须大于0');
          return false;
        }
      }
    }
    wx.showModal({
      title: '提示',
      content: type ? `是否充值？` : `是否开卡？`,
      success: res => {
        if (res.confirm) {
          this.excutePost(param);
        }
      }
    })
  },


  excutePost(param) {
    Object.assign(param, {
      full_name: this.data.full_name,
      tel: this.data.tel,
      village_name: this.data.village_name,
      village_id: this.data.village_id,
      card: app.trimAll(this.data.card_number),
      money: this.data.money,
      give: this.data.give,
      template_id: this.data.moneyIndex == -1 || (this.data.showCard == false && this.data.money == 0) ? '' : this.data.template_id,
      promotion_id: this.promotion_id
    })
    wx.showLoading({
      mask: true,
    })
    app.ajax({
      url: 'Partner/WaterCard/waterCardRecharge',
      method: "POST",
      data: param,
      success: res => {
        wx.hideLoading()
        var flag = res.data;
        if (flag.code > 0) {
          app.showToast(flag.message, "success");
          let resetData = { //需要重置的数据
            give: 0,
            money: 0,
            depositIndex: 0,
            moneyIndex: '',
          }
          if (!this.data.showCard) {
            Object.assign(resetData, {
              moneyIndex: -1,
              showCard: false,
              card_number: '',
              full_name: "",
              tel: "",
              cardInfo: "",
              isShow: true,
              btnTxt: APPLY_TEXT,
              promotions: [],
              village_name: '',
              village_id: "",
            })
          } else {
            this.getWaterCard(app.trimAll(this.data.card_number), false)
          }
          this.setData(resetData)
          wx.pageScrollTo({
            scrollTop: 0,
            duration: 300
          })
          this.getBalance();
        } else {
          app.showToast(flag.message)
        }
      },
      error: e => {
        wx.hideLoading();
        app.showToast("网络错误")
      }
    })
  },


  //关闭特殊水卡提示
  closeTips() {
    this.setData({
      specialTips: false
    })
  },


  //跳转到特殊水卡充值界面
  navSpecialRecharge() {
    let _self = this;
    wx.navigateTo({
      url: '../specialApply/index?type=2',
      success: function (res) {
        res.eventChannel.emit("acceptDataFromWaterRecharge", {
          card_number: app.trimAll(_self.data.card_number)
        });
      }
    })
  },

})